package org.jflame.commons.valid;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;

import org.apache.commons.lang3.tuple.ImmutablePair;

/**
 * 正则表达式缓存池. 生成的Pattern将放入缓存池,避免每次编译
 * 
 * @author charles.zhang
 */
public class RegexPool {

    private static Map<String,Pattern> PATTERN_MAP = new ConcurrentHashMap<>();
    private static Map<ImmutablePair<String,Integer>,Pattern> PATTERN_WITH_FLAG_MAP = new ConcurrentHashMap<>();

    private RegexPool() {
    }

    /**
     * 给定正则字符串生成Pattern
     * 
     * @param regex 正则字符串
     * @return
     */
    public static Pattern pattern(String regex) {
        return PATTERN_MAP.computeIfAbsent(regex, Pattern::compile);
    }

    /**
     * 给定正则字符串生成Pattern
     * 
     * @param regex 正则字符串
     * @param flag 模式标志. 如Pattern.CASE_INSENSITIVE
     * @return
     */
    public static Pattern pattern(String regex, int flag) {
        return PATTERN_WITH_FLAG_MAP.computeIfAbsent(ImmutablePair.of(regex, flag),
                k -> Pattern.compile(k.getLeft(), k.getRight()));
    }
}
